package factory;

import client.RpcClient;
import client.handle.ClienInboundHandle;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import support.Constans;
import support.anno.Config;

import java.net.InetSocketAddress;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class RpcClientFactory {
    static Logger logger = LoggerFactory.getLogger(RpcClientFactory.class);

    static Map<String,RpcClient> cache = new ConcurrentHashMap<>();

    static public RpcClient getOne(){
        RpcClient rpcClient = cache.get(Constans.CENTER_KEY);
        if(rpcClient==null){
            logger.warn("Client Key 找不到对应的注册中心客户端...");
        }
        return rpcClient;
    }

    //删除下线ip的客户端缓存
    static public void removeCacheCLient(InetSocketAddress address){
        String key = getKey(address.getHostString(), address.getPort(), null);

        List<String> delKeys = new LinkedList<>();
        cache.forEach((k,v)->{
            if(k.indexOf(key)!=-1){
                delKeys.add(k);
            }
        });

        logger.info("查找到删除的key list ： {}",delKeys);
        delKeys.forEach(dk->{
            try {
                cache.get(dk).closeCLinet();
            } catch (InterruptedException e) {
                logger.error("关闭出现异常...");
                e.printStackTrace();
            }
            cache.remove(dk);
        });

    }

    private static String getKey(String h,int p,String iname){
        StringBuilder key = new StringBuilder();
        key.append(h);
        key.append(":");
        key.append(p);
        if(iname!=null){
            key.append(":");
            key.append(iname);
        }

        //给这个连接生成一个key，下次调用根据这个key决定走那个通道
        String ks = key.toString();
        return ks;
    }

    static public RpcClient getClient(String h,int p,String iname){
        String ks = getKey(h, p, iname);

        synchronized (RpcClientFactory.class) {

            RpcClient rpcClient = cache.get(ks);
            RpcClient res =null;
            if (rpcClient == null) {
                logger.info("缓存没有，创建新的连接...");
                rpcClient = new RpcClient(h, p,new ClienInboundHandle());
                try {
                    rpcClient.conn();
                } catch (Exception e) {
                    e.printStackTrace();
                    return null;
                }

                //连接成功才进缓存
                cache.put(ks, rpcClient);
                res = rpcClient;
            }else
                res = rpcClient;

            return res;
        }
    }
}
